<template>
  <div :class="{'edit-mode': isEdit, 'mt': !isEdit}" class="sub-table-content">
    <div class="top">
      <div style="flex-shrink: 0;"><Title :element="element" isTable /></div>
      <div v-if="(element.options.required || !!(requiredKeys && requiredKeys.includes(element.key))) && isEdit" class="is-required">*</div>
      <template v-if="element.options && element.options.tip">
        <div v-if="element.options.tip.length < 20" class="tip">{{ element.options.tip }}</div>
        <ToolTip v-else :content="element.options.tip" class="tip" />
      </template>
      <div class="flex"/>
      <template v-if="!element.options.hideOperation && !element.options.isCard">
        <PlainCreateBtn v-if="isEdit" @click="addCol">添加</PlainCreateBtn>
        <el-button v-if="isEdit" size="small" class="delete-btn" @click="deleteItem()">删除</el-button>
      </template>
    </div>
    <div v-if="element.options && element.options.statistics && element.options.statistics.length && statistics.length" class="statistics-list">
      <dataDisplay
        :data-list="statistics"
        type="row"
        style="width:100%;"/>
    </div>
    <template v-if="!element.options.isCard">
      <el-table
        ref="subTableRef"
        :data="handelTableData(listData)"
        :border="true"
        :max-height="tableHeight"
        empty-text="暂无数据"
        fit
        element-loading-text="加载中..."
        header-cell-class-name="dynamic-edit-table-cell"
        @select="selectTable"
        @select-all="selectTable"
      >
        <EmptyPlaceholder slot="empty" empty-text="暂无数据" is-border mode="table" style="padding-bottom: 0;white-space: nowrap;" />
        <el-table-column v-if="isEdit && !element.options.hideOperation" :key="element.key" :width="50" :fixed="element.subform.length > 7 && !showMobilePage?'left':false" align="center" type="selection" />
        <el-table-column v-if="!element.options.hideOperation" :key="element.key + 1" :width="50" align="left" label="序号" >
          <template slot-scope="scope">
            <div class="center">{{ scope.$index +1 }}</div>
          </template>
        </el-table-column>
        <template v-for="(colItem) in element.subform">
          <el-table-column v-if="isShow(colItem)" :key="colItem.key" :label="colItem.name" v-bind="getBind(colItem)">
            <template slot="header" slot-scope="scope">
              <div class="flex-center">
                <span v-if="isEdit && colItem.options.required" style="color: #f56c6c;margin-right:4px;">*</span>
                <div class="label">{{ scope.column.label }} </div>
                <ToolTip v-if="colItem.options && colItem.options.tip" :icon="tipIcon" :content="colItem.options.tip" class="ml5" />
              </div>
            </template>
            <template slot-scope="scope">
              <div v-if="isEdit" :class="{'pad8': hasPadding.includes(colItem.type) || (colItem.options && colItem.options.readonly)}" class="edit-container">
                <FormMakeElement
                  v-model="scope.row[colItem.key]"
                  :is-in-detail="isInDetail"
                  :form-options="formOptions"
                  :element="colItem"
                  :subform-index="scope.$index"
                  :is-weibo-or-weixin="isWeiboOrWeixin"
                  :use-inner-upload="useInnerUpload"
                  :subform-element="element"
                  is-table
                  @subformInputChange="subformInputChange"
                  @getFocus="getFocus($event, scope.row, scope.$index)"
                  @handleFormUserSelect="handleFormUserSelect($event, scope.$index)" />
              </div>
              <FormMakeElement
                v-else
                v-model="scope.row[colItem.key]"
                :subform-index="scope.$index"
                :subform-element="element"
                :is-weibo-or-weixin="isWeiboOrWeixin"
                :use-inner-upload="useInnerUpload"
                :is-in-detail="isInDetail"
                :form-options="formOptions"
                :element="colItem"
                is-detail
                is-table />
            </template>
          </el-table-column>
        </template>
        <el-table-column
          v-if="isEdit && !element.options.hideOperation"
          :width="operateWidth"
          :fixed="element.subform.length > 3?'right':false"
          :align="operateAlign"
          label="操作">
          <template slot-scope="scope">
            <div v-if="!showMobilePage" class="flex-center btn-padding">
              <div class="button-text br" @click="copyCol(scope.row)">复制</div>
              <div class="button-text" @click="deleteItem(scope.row)">删除</div>
            </div>
            <tableOperateBtn v-else>
              <el-dropdown-item @click.native="copyCol(scope.row)">
                <div>复制</div>
              </el-dropdown-item>
              <el-dropdown-item @click.native="deleteItem(scope.row)">
                <div>删除</div>
              </el-dropdown-item>
            </tableOperateBtn>
          </template>
        </el-table-column>
      </el-table>
      <SubSearchView
        v-if="isShowSubSearchView"
        :sub-params="subParams"
        :row-id="rowId"
        :style="{top: `-${rowTopIndex}px`}"
        v-model="subSearchValue"
        class="sub-search-view"
        @selectHistory="selectHistory"
        @deleteSubHistory="getSubformHistory"
        @close="close()" />
      <!-- <EmptyPlaceholder v-else empty-text="暂无数据" /> -->
      <div class="table-footer">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <span style="flex:1"/>
        <el-pagination
          v-if="listData.length > 10"
          :page-sizes="[10, 20, 30, 50, 100, 250, 500]"
          :current-page="curPage"
          :page-size="perPage"
          :total="listData.length"
          :layout="showMobilePage?pageLayout:'total, sizes, prev, pager, next, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </template>
    <TableCardContent
      v-else
      :element="element"
      :is-detail="!isEdit"
      :is-in-detail="isInDetail"
      :form-options="formOptions"
      :is-show-element="isShow"
      @addCol="addCol"
      @copyCol="copyCol"
      @deleteItem="deleteItem"
    />
  </div>
</template>

<script>
import { mapState } from 'vuex';
// img
import tipIcon from '@/assets/process/tip.png';
import incomeAmount from '@/assets/dataDisplay/icon_45.png';
// components
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import FormMakeElement from './FormMakeElement';
import TableCardContent from './Subtable/tableCardContent';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import SubSearchView from './Subtable/searchView';
// mixins
import tableSelections from '@/mixins/tableSelections';
import ElMessage from '@/utils/message';
import math from '@/utils/math';
import { userChange } from '@/views/legal/process/components/formMake/utils/userField.js';
import { getMonthStr } from '@/utils';
import { validateField, fieldPermissionJudge } from '@/views/approvalModule/utils/filter.js';
// api
import { getLeaderByUser, getSubformHistory } from '@/api/process';
import Title from './Title';
import mobileTable from '@/mixins/mobileTable';
// import { forEachFormOptions } from '@/utils/formMakeUtils.js';
export default {
  name: 'SubTableContent',
  components: { Title, dataDisplay, FormMakeElement, EmptyPlaceholder, SubSearchView, TableCardContent },
  mixins: [tableSelections, mobileTable],
  model: {
    prop: 'listData',
    event: 'changeData'
  },
  props: {
    listData: {
      type: Array,
      default: () => {
        return [{}];
      }
    },
    element: {
      type: Object,
      default: null
    },
    isWeiboOrWeixin: { // 是否双微发文审核，区别是上传的接口不同
      type: Boolean,
      default: false
    },
    useInnerUpload: { // 是否使用内网上传
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    isInDetail: { // 是否详情页展示，isDetail可能因为事件而改变，导致实际在详情页而 isDetail 为false，这个属性不会改变，详情页永远为true
      type: Boolean,
      default: false
    },
    tableHeight: {
      type: Number | String,
      default: null
    },
    formOptions: {
      type: Object,
      default: () => ({})
    },
    processStatus: {// 审批详情状态
      type: Number,
      default: null
    },
    isSetDefault: {
      type: Boolean,
      default: false
    },
    requiredKeys: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tipIcon, incomeAmount,
      curPage: 1,
      perPage: 10,
      idKey: '_id',
      tableRefName: 'subTableRef',
      hasPadding: ['radio', 'checkbox', 'switch', 'upAttachment'],
      subSearchValue: {},
      isShowSubSearchView: false,
      rowId: '',
      subParams: {},
      rowTopIndex: 0 // 历史记录弹窗定位的表格行
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage,
      'fieldPermissions': state => state.formMake.fieldPermissions
    }),
    statistics() {
      const statistics = this.element.options.statistics || [];
      const listData = this.listData;
      const keys = [];
      statistics.forEach(i => {
        const item = this.element.subform.find(j => j.key === i);
        if (item) keys.push({ data: null, label: item.name + '：', icon: incomeAmount, key: i, unit: item.type === 'input' && item.options.isShowPercentage ? '%' : '' });
      });
      keys.forEach(i => {
        let ans = null;
        listData.forEach(j => {
          if (j[i.key] || j[i.key] === 0) {
            ans = ans === null ? Number(j[i.key]) : math.add(ans, Number(j[i.key]));
          }
        });
        i.data = ans;
        i.width = 'auto';
      });
      return keys;
    }
  },
  created() {
    if (!this.element.options.isCard) this.getSubformHistory();
  },
  mounted() {
    if (!this.listData || this.listData.length === 0) {
      if (this.element.options.required || (this.requiredKeys && this.requiredKeys.includes(this.element.key) && this.element.type !== 'switch')) this.addCol();
    } else {
      this.setId();
    }
  },
  methods: {
    getSubformHistory() {
      const params = {
        subFormKey: this.element.key,
        page: 1,
        perPage: 3
      };
      getSubformHistory(params).then(res => {
        if (res.code === 200) {
          this.subParams.isHistoryData = !!res.data.length;
        }
      }).catch(err => console.error(err.message));
    },
    handelTableData(tableData) {
      const pageData = tableData && tableData.slice((this.curPage - 1) * this.perPage, this.curPage * this.perPage) || [];
      this.setSelectRow && this.setSelectRow(pageData);
      return pageData;
    },
    selectHistory(data, row) {
      this.isShowSubSearchView = false;
      data.key = this.element.key;
      this.$emit('selectHistory', data);
    },
    // table
    handleSizeChange(val) {
      this.perPage = val;
    },
    handleCurrentChange(val) {
      this.curPage = val;
    },
    // tool
    deleteItem(item = null) {
      let select = [];
      if (item) {
        select = [item];
      } else {
        select = this.multipleSelectionAll || [];
      }
      if (select.length === 0) {
        ElMessage.warning('请选择数据');
        return;
      }
      this.$confirm('请确认是否删除所选的数据', '', {
        confirmButtonText: '确定', type: 'warning',
        showClose: false, center: true, iconClass: 'charge-icon',
        customClass: `del-message del-message-cancel ${this.showMobilePage ? ' mobile-message' : ''}`
      }).then(() => {
        const ids = select.map(i => i._id);
        const listData = this.listData.filter(i => {
          return !ids.includes(i._id);
        });
        this.clearMixinSelection();
        this.$emit('changeData', listData);
        this.handleCurrentChange(1);
      });
    },
    addCol() {
      const _id = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
      const params = {};
      this.element.subform.forEach(j => {
        this.$set(params, j.key, Array.isArray(j.value) ? [] : '');
      });
      params._id = _id;
      this.listData.push(params);
      this.getInit(this.listData[this.listData.length - 1]);
    },
    copyCol(item) {
      const cloneItem = _.cloneDeep(item);
      cloneItem._id = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
      this.listData.push(cloneItem);
    },
    setId() {
      this.listData.forEach(i => {
        if (!i._id) {
          i._id = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
        }
        this.element.subform.forEach(j => {
          if (!Object.hasOwnProperty.call(i, j.key)) {
            this.$set(i, j.key, Array.isArray(j.value) ? [] : '');
          }
        });
      });
    },
    getInit(ans) {
      this.element.subform.forEach(async i => {
        let result = i.value;
        if (i.type === 'date') {
          const isDefaultNowTime = i.options.isDefaultNowTime;
          const currentMonth = new Date().valueOf();
          const { entryTime, dimissionTime } = this.userInfo;
          const userEntryTime = entryTime && entryTime * 1000 || null;
          const userResignTime = dimissionTime && dimissionTime * 1000 || null;
          const lastMonth = getMonthStr(-1);
          const nextMonth = getMonthStr(1);
          const dateMap = ['', currentMonth, userEntryTime, userResignTime, lastMonth, nextMonth];
          result = dateMap[isDefaultNowTime];
        } else if (i.type === 'department') {
          result = this.setDepartmentDefault(i);
        } else if (i.type === 'user') {
          const res = await this.setUserDefault(i);
          if (res) result = res;
        } else if (i.type === 'post' && i.options.defaultPost === 1) {
          // 职位跟随 创建人职位
          const { post } = this.userInfo;
          const currUserPost = { id: post, name: post };
          result = i.options.isMultiple ? [currUserPost] : currUserPost;
        } else if (i.type === 'upAttachment') {
          result = [];
        } else {
          result = _.cloneDeep(i.value);
        }
        this.$set(ans, i.key, result);
        if (i.type === 'user') {
          // 如果有的话，触发关联字段
          this.userChange(i);
        }
      });
    },
    changeData() {
      this.$emit('changeData', this.listData);
    },
    getBind(colItem) {
      const minWidth = 120;
      let width = '';
      const noWidth = ['switch', 'radio', 'checkbox', 'upAttachment', 'createUser', 'createTime', 'workflowId'];
      if (this.isEdit) {
        if (colItem.type === 'upAttachment') {
          width = 200;
        }
        if (!noWidth.includes(colItem.type)) {
          width = (colItem.options && colItem.options.width) || 240;
        }
      }
      if (this.isInDetail && !this.isEdit && colItem.options && colItem.options.detailWidth) {
        width = colItem.options.detailWidth;
      }
      return {
        align: 'left',
        minWidth,
        width: width || minWidth
      };
    },
    subformInputChange(value) {
      this.subSearchValue = value;
    },
    handleFormUserSelect(data, index) {
      data.subformRowIndex = index;
      this.$emit('handleFormUserSelect', data);
    },

    // 获取主管
    async getLeaderByUserApi(element) {
      const type = element.options.defaultValue - 2;
      const ids = `${this.userInfo.id}`;
      if (!ids) { return []; }
      const result = await getLeaderByUser({ ids, type }).then(res => {
        if (res.code === 200) {
          return res.data;
        }
      }).catch(err => {
        console.error(err.message);
      });
      return result;
    },
    userChange(changeElement) {
      const that = this;
      const index = this.listData.length - 1;
      userChange(changeElement, this.formOptions, {
        userInfo: this.userInfo,
        subformIndex: index,
        handleFormUserSelect: (element, value) => {
          const cloneElement = _.cloneDeep(element);
          if (value && !Array.isArray(value)) cloneElement['_post'] = value && value.post || null;
          cloneElement._postValue = { ...value };
          that.handleFormUserSelect(cloneElement, index);
        }
      });
    },
    // 设置默认用户
    async setUserDefault(item) {
      const multiple = item.options.multiple;
      const defaultValue = item.options.defaultValue;
      if (defaultValue === 1) {
        const user = { id: this.userInfo.id, userName: this.userInfo.userName, post: this.userInfo.post };
        const ans = multiple ? [user] : user;
        return ans;
      } else if (defaultValue > 1 && defaultValue < 5) {
        // 只有不需要关联其他字段的人员字段会请求
        const result = await this.getLeaderByUserApi(item);
        return multiple ? result : result[0];
      }
      return multiple ? [] : '';
    },
    // 设置默认部门
    setDepartmentDefault(item) {
      const multiple = item.options.multiple;
      const defaultValue = item.options.defaultValue;
      if (this.userInfo) {
        if (defaultValue === 0) {
        // 回填当前用户一级部门
          if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
            const dept = this.userInfo.deptName[0];
            return multiple ? [{ id: dept.id, name: dept.name }] : { id: dept.id, name: dept.name };
          }
        } else if (defaultValue === 1) {
        // 回填当前用户第一个当前部门
          if (this.userInfo.subDepartment && this.userInfo.subDepartment.length > 0 && this.userInfo.subDepartment[0].id) {
            const dept = this.userInfo.subDepartment[0];
            return multiple ? [{ id: dept.id, name: dept.name }] : { id: dept.id, name: dept.name };
          } else if (this.userInfo.deptName && this.userInfo.deptName.length) {
            const dept = this.userInfo.deptName[0];
            return multiple ? [{ id: dept.id, name: dept.name }] : { id: dept.id, name: dept.name };
          }
        }
      }
      return multiple ? [] : '';
    },
    isShow(element) {
      if (this.isSetDefault) return true;
      if (!fieldPermissionJudge(element, this.fieldPermissions)) {
        return false;
      }
      const validateResult = this.validateField(element);
      if (validateResult !== null) {
        return validateResult;
      }
      if (!element.options) return true;
      if (this.isInDetail && element.options.detailHide) {
        return false;
      } else if (!this.isInDetail && element.options.createHide) {
        return false;
      }
      return true;
    },
    // 判断组件是否可以展示
    validateField(element) {
      // 权重：字段权限＞流程事件＞字段显隐条件＞字段属性
      return validateField(element, this.formOptions, this.processStatus);
    },
    getRows() {
      let rows = 1;
      this.element.subform && this.element.subform.map(it => {
        if (it.options.rows && it.options.rows > rows) {
          rows = it.options.rows;
        }
      });
      return rows;
    },
    subSearchViewTop(rows) {
      if (rows === 1) {
        return 48;
      } else if (rows === 2) {
        return 55;
      } else {
        return 55 + (rows - 2) * 21;
      }
    },
    getFocus(val, row, index) {
      this.rowId = row._id;
      this.rowTopIndex = this.handelTableData(this.listData).length - index - 1;
      const rows = this.getRows();
      const height = this.subSearchViewTop(rows);
      this.rowTopIndex = this.rowTopIndex * height;
      this.subParams = { ...this.subParams, ...this.element };
      this.subSearchValue = val;
      this.isShowSubSearchView = true;
    },
    close() {
      this.isShowSubSearchView = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.sub-table-content {
  ::v-deep .el-table__empty-block {
    margin: 0 auto;
    min-height: 48px;
    height: 48px !important;
  }
}
.mt {
  margin-top: 12px;
}
.top {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  .tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
  }
}
.statistics-list {margin-bottom: 12px;}
.delete-btn {
  color: #666666;
  border-color: #ddd;
  background-color: #fff;
  padding: 7px 8px;
}
.center {
  display: flex;
  justify-content: center;
}
.flex {
  flex: 1;
}
.table-footer {
  margin-top:12px; display:flex;
  margin-bottom: 10px;
}
.edit-mode {
  &::v-deep {
    .el-select__caret {
      color: #333;
    }
    .el-table__row {
      td {
        padding: 0;
        background-color: #fff !important;
      }
      .cell {
        padding: 0;
      }
    }
    .fb-upload-container {
      z-index: 0 !important;
    }
  }
  .edit-container {
    &::v-deep {
      .el-input__inner,.user-select-input,.formula-input-inner {
        height: 47px;
        border-radius: 0;
        background-color: transparent;
        border-color: transparent;
      }
      .formula-input-inner {
        line-height: 47px;
        background-color: transparent;
      }
      .formula-input-container {
        width: 100%;
      }
      .el-textarea__inner {
        border-color: transparent;
      }
    }
  }
  .pad8 {
    padding: 0 8px;
  }
}
.flex-center {
  display: flex;
  align-items: center;
}
.is-required {
  color: #F56C6C;
  margin-left: 3px;
}
.btn-padding {
  padding: 0 10px;
  min-height: 32px;
}
.sub-search-view {
  position: relative;
  z-index: 10;
  background-color: #fff;
}
</style>
